var express = require('express'),
	path = require('path'),
	http = require('http'),
	mongoose = require('mongoose'),
	fsx = require('fs-extra');

// models
var Dish = require('./models/dish');

// declare server
var app = express();

// database connection
mongoose.connect('mongodb://localhost/ecomm_database');

// config server
app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.use(express.favicon(path.join(__dirname, 'public/img/favicon.ico'))); 
	app.use(express.bodyParser());
	//app.use(express.methodOverride());
	app.use(app.router);
	app.use(express.static(path.join(__dirname,"public")));
	app.use(express.errorHandler({
		dumpExceptions: true,
		showStack: true
	}));
});

// set up
app.get('/', function(req, res){
	res.sendfile('./public/index.html');
});

// route processing
app.get('/api', function(req, res){
	res.send('Ecomm API is running on port 8888');
});

app.get('/api/menu', function(req, res){
	return Dish.find(function(err, dishes){
		if(!err){
			return res.send(dishes);
		}else{
			return console.log('** ' + err);
		}
	});
});

app.get('/api/menu/page/:pg/:limit', function(req, res){
	var page = parseInt(req.params.pg),
		limit = parseInt(req.params.limit);
	return Dish
	.find()
	.skip((page - 1) * limit)
	.limit(limit)
	.sort({name: 1})
	.exec(function(err, dishes){
		if(err)
			console.log('** Paging error: ' + err);

		res.send(dishes);
	});
})

app.get('/api/deleteAll', function(req, res){
	Dish.remove(function(err){
		if(err){
			console.log('** Delete all error: ' + err)
		}else{
			console.log('Deleted all...');
			res.send('OK');
		}
	});
});

app.get('/api/init', function(req, res){
	fsx.readFile('./data/data.json','utf-8',function(err, rawMenu){
		if(err)
			console.log("** Readfile eror: " + err);
		else{
			var data = JSON.parse(rawMenu);
			for(var i=0;i<data.length;i++){
				new Dish({
					name: data[i].name,
					description: data[i].description,
					style: data[i].style
				}).save(function(err){
					if(err){
						console.log("** " + err);
						res.send('ERR');
					}					
				});
			}
			console.log('Init done...');
			Dish.find(function(err, dishes){
				if(!err)
					res.send(dishes);

			});
		}
	});
});

// app.post('/api/menu', function(req, res){
// 	var dish = new Dish({
// 		name: req.body.name,
// 		description: req.body.description,
// 		style: req.body.style
// 	}).save(function(err){
// 		if(err)
// 			console.log('** ' + err);
// 		else{
// 			console.log('Dish is created!!!');
// 			return res.send(dish);
// 		}
// 	});
// });

app.post('/api/menu', function(req, res){
	console.log('Received create request.');

	// var dish = new Dish({
	// 	name: req.body.name,
	// 	description: req.body.description,
	// 	style: req.body.style
	// }).save(function(err){
	// 	if(err)
	// 		console.log('** ' + err);
	// 	else{
	// 		console.log('Dish is created!!!');
	// 		return res.send(dish);
	// 	}
	// });

	Dish.createNewDish(req.body.name, req.body.description, req.body.style, function(err, dish){
		if(err)
			console.log('** Err: ' + err);
		else
			console.log('Created');

		res.send(dish);
	});
});

app.get('/api/menu/:id', function(req, res){
	console.log('Received request for dish ' + req.params.id);
	return Dish.findOne({'_id':req.params.id}, function(err, dish){
		if(!err){
			return res.send(dish);
		}else{			
			return console.log("** Get error: " + err);
		}
	});
});

// app.get('/api/menu/:id', function(req, res){
// 	console.log('Received request for dish ' + req.params.id);

// 	return Dish.findById(req.params.id, function(err, dish){
// 		if(err){
// 			return console.log("** Error: " + err)
// 		}else{
// 			dish.modified = Date.now();
// 			dish.save(function(err){
// 				if(err)
// 					console.log('** Error: ' + err);
// 			});

// 			return console.log(dish);
// 		}
// 	});
// });

app.put('/api/menu/:id',function(req, res){
	console.log('Received update request for dish ' + req.params.id);
	// return Dish.findOne({'_id' : req.params.id}, function(err, dish){
	// 	dish.name = req.body.name;
	// 	dish.description = req.body.description;
	// 	dish.style = req.body.style;
	// 	// update
	// 	dish.save(function(err){
	// 		if(err)
	// 			console.log('** ' + err);
	// 		else
	// 			console.log('Updated successfully');

	// 		return res.send(dish);
	// 	});
	// });

	return Dish.findOne({'_id':req.params.id}, function(err, dish){
		dish.updateDish(req.body.name, req.body.description, req.body.style, function(err){
			if(err)
				console.log('** ' + err);
			else
				console.log('Updated');

			res.send(dish);
		});
	});
});

app.delete('/api/menu/:id', function(req, res){
	console.log('Received delete request for dish ' + req.params.id);
	// return Dish.findOne({'_id' : req.params.id}, function(err, dish){
	// 	if(dish){
	// 		dish.remove(function(err, dish){
	// 			if (err) return console.log("** Delete error: " + err);
 //  				Dish.findById(dish._id, function (err, dish) {
 //    				console.log(dish) // null
 //  				});
	// 		});
	// 		return res.send('');
	// 	}
	// });

	return Dish.deleteDish(req.params.id, function(err){
		if(err)
			console.log(err);

		res.send('');
	});
});

/**
 *
 * Summary
 *
 * GET  :       /loginTest
 * GET  :       /login
 * POST :       /login
 * GET  :       /auth/facebook
 * GET  :       /auth/facebook/callback
 * GET  :       /auth/google
 * GET  :       /auth/google/callback
 * GET  :       /signup
 * POST :       /signup
 * GET  :       /profileTest
 * GET  :       /logout
 * POST :       /recovery
 * POST :       /recovery/checkUsername
 * POST :       /recovery/checkContact
 * GET  :       /resetPassword/:token
 * GET  :       /resetPassword
 *
 *
 */

// server listen
var server = http.createServer(app);

server.listen(app.get('port'),function(){
	console.log('Listenning at port 3000...');
});
